import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ProductConsumer {
    private BlockingQueue<String> queue;
    private boolean flag = true;

    public static void main(String[] args) {
        new ProductConsumer().test();
    }
    public void test() {
        Product product = new Product(queue);
        Thread p = new Thread(product);
        p.start();
        for(int i=0;i<4;i++){
            Consumer consumer = new Consumer(queue);
            Thread c = new Thread(consumer);
            c.start();
        }
    }

    public ProductConsumer() {
        queue = new ArrayBlockingQueue<>(10000);
    }
    class Product implements Runnable {
        private BlockingQueue<String> queue = null;
        public Product(BlockingQueue<String> queue) {
            this.queue = queue;
        }
        @Override
        public void run() {
            while (flag) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String n = String.valueOf((int) (Math.random() * 10));
                try {
                    queue.put(n);
                    System.out.println(Thread.currentThread().getName() + "生产size=" + queue.size() +"生产了     " + n);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class Consumer implements Runnable {
        private BlockingQueue<String> queue;
        public Consumer(BlockingQueue<String> queue) {
            this.queue = queue;
        }
        @Override
        public void run() {
            while (flag) {
                try {
                    Thread.sleep(400);
                    String takeVal = queue.take();
                    System.out.println(Thread.currentThread().getName() + "消费size=" + queue.size() + ",消费了 " + takeVal);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}